package com.itheima.controller;

import com.aliyuncs.exceptions.ClientException;
import com.itheima.constant.MessageConstant;
import com.itheima.constant.RedisMessageConstant;
import com.itheima.entity.Result;
import com.itheima.utils.SMSUtils;
import com.itheima.utils.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

/**
 * @Author: bowen
 * @Date: 2019/6/29 15:12
 * @Description:验证码
 */
@RestController
@RequestMapping("/validateCode")
public class ValidateCodeController {


	@Autowired
	JedisPool jedisPool;

	/**
	 *  @描述：发送验证码
	 */
	@RequestMapping("/send4Order")
	public Result send4Order(String telephone) {

		//1.生成验证码
		String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
		//2.发送验证码
		try {
			SMSUtils.sendShortMessage(SMSUtils.VALIDATE_ORDER, telephone, validateCode);
		} catch (ClientException e) {
			e.printStackTrace();
			return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
		}
		//3.redis缓存验证码
		jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_ORDER, 5*60, validateCode);


	  return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
	}


	/**
	 *  @描述：发送登录验证码
	 */
	@RequestMapping("/send4Login")
	public Result send4Login(String telephone) {

		//1.生成验证码
		String validateCode = ValidateCodeUtils.generateValidateCode(6).toString();
		//2.发送验证码
		try {
			SMSUtils.sendShortMessage(SMSUtils.VALIDATE_LOGIN, telephone, validateCode);
		} catch (ClientException e) {
			e.printStackTrace();
			return new Result(false, MessageConstant.SEND_VALIDATECODE_FAIL);
		}
		//3.redis缓存验证码
		jedisPool.getResource().setex(telephone+ RedisMessageConstant.SENDTYPE_LOGIN, 5*60, validateCode);


		return new Result(true, MessageConstant.SEND_VALIDATECODE_SUCCESS);
	}


}
